package sync;

import sendRecieveWrapper.ICallerResponseTypeWrapper;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ResponseManager {
	/**自增分配id**/
	private int increid;
	
	/**
	 * 回调列表
	 */
	private List<Response> responseList = new LinkedList<>();
	
	
	public void buildRequest(Method method, Object[] args, RpcRequest request, ICallerResponseTypeWrapper rpcHandler)
	{
		Response response = new Response();
		response.setRpcHandler(rpcHandler);
		add(response);
		//response.setRecieveWrapper(recieveWrapper);
		request.setRequestId(response.getRestquestId());
	}


	public synchronized Response getResponse(int requestId)
	{
		Iterator<Response> it = responseList.iterator();
		while(it.hasNext())
		{
			Response response = it.next();
			if(response.getRestquestId()!=requestId)
				continue;
			it.remove();
			return response;
		}
		return null;
	}
	
	
	private synchronized void add(Response response)
	{
		response.setRestquestId(increid++);
		responseList.add(response);
	}
	
	class Response
	{
		private int restquestId;
		private String expection;
		private ICallerResponseTypeWrapper rpcHandler;


		public String getExpection() {
			return expection;
		}
		public void setExpection(String expection) {
			this.expection = expection;
		}
		public int getRestquestId() {
			return restquestId;
		}
		public void setRestquestId(int restquestId) {
			this.restquestId = restquestId;
		}

		public ICallerResponseTypeWrapper getRpcHandler() {
			return rpcHandler;
		}

		public void setRpcHandler(ICallerResponseTypeWrapper rpcHandler) {
			this.rpcHandler = rpcHandler;
		}
	}

}
